<?php

/*
 *	Framework namespace
 */
namespace Nano
{
	/*
	 *	Config class
	 *
	 *	@extends \Kernel
	 */
	class Config extends \Kernel
	{
		/*
		 *	$path	string	Path to config files (relative to application)
		 */
		public $path = 'configs';
		
		/*
		 *	$extension	string	Configuration extension
		 */
		public $extension = '.xml';
		
		/*
		 *	$readonly	boolean	Read only flag
		 */
		public $readonly = true;
		
		/*
		 *	$configs	array	Loaded configs
		 *
		 *	@private
		 */
		private $configs = array();
		
		/*
		 *	Constructor
		 */
		public function __construct()
		{
			$this->path = APPLICATION.DS.$this->path;
			
			if(!Filesystem::is('dir', $this->path))
			{
				throw new \Exception(__CLASS__.': Configuration path does not exists');
			}
			
			if(!Filesystem::is('readable', $this->path))
			{
				throw new \Exception(__CLASS__.': Configuration path is not readable');
			}
			
			if(!$this->readonly && !Filesystem::is('writable', $this->path))
			{
				throw new \Exception(__CLASS__.': Configuration path is not writeable');
			}
			
		}
		
		/*
		 *	Return data
		 *
		 *	@param	string	Configuration
		 *	@param	string	Path to key
		 *
		 *	@return	string	On success
		 *	@return	boolean	false On failre
		 *	@return	null	If key does not exists
		 */
		public function get($config, $path)
		{
			static $cache = array();
			
			if(key_exists($path, $cache))
			{
				return $cache[$path];
			}
			
			if(key_exists($config, $this->configs))
			{
				return false;
			}
			
			$conf = $this->config[$config];
			
			foreach(explode('/', $path) as $key)
			{
				if($conf === null)
				{
					return null;
				}
			
				$conf = isset($conf[$key]) ? $conf[$key] : null;
			}
			
			$cache[$path] = $conf;
			
			return $conf;
		}
		
		/*
		 *	Load config
		 *
		 *	@param	string	Config file
		 */
		public function load($name, $strict = true)
		{
			if(key_exists(strtolower($name), $this->configs))
			{
				return $this->configs[strtolower($name)];
			}
			
			$file = $this->path.DS.$name.$this->extension;
			
			$this->files[$file] = false;
			
			if(!Filesystem::exists($file))
			{
				if($strict)
				{
					throw new \Exception(__CLASS__.': Configuration "'.$name.'" does not exists');
				}
				else
				{
					debug(__CLASS__.': Configuration "'.$name.'" does not exists');
				}
			}
			
			$config = Filesystem::get($file);
			
			if(empty($config))
			{
				if($strict)
				{
					throw new \Exception(__CLASS__.': Configuration "'.$name.'" is empty');
				}
				else
				{
					debug(__CLASS__.': Configuration "'.$name.'" is empty');
				}
			}
			
			return $this->configs[strtolower($name)] = XML::parse($config);
		}
	}
}